package com.mdp.im.core.publish.action.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mdp.core.api.Sequence;
import com.mdp.core.err.BizException;
import com.mdp.im.core.entity.ImGroup;
import com.mdp.im.core.entity.ImGroupUser;
import com.mdp.im.core.publish.action.AbstractPublishAction;
import com.mdp.im.core.publish.api.action.PublishAction;
import com.mdp.im.core.publish.api.Publisher;
import com.mdp.im.core.publish.api.StorePublisher;
import com.mdp.im.core.service.ImGroupMessageService;
import com.mdp.im.core.service.ImGroupService;
import com.mdp.im.core.service.ImGroupUserService;
import com.mdp.im.core.service.ImLoginUtils;
import com.mdp.im.core.utils.msg.Action;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;


/**
 * 群组创建消息处理器
 * 
 * @author chenyc
 * @date 2018/5/28
 */
@Service("pushChannelGroupCreatedAction")
public class ChannelGroupCreatedAction extends AbstractPublishAction implements PublishAction {
	
	@Autowired
	Sequence seqService;
	@Autowired
	ImGroupService groupService;
	@Autowired
	ImGroupUserService groupUserService;
	
	@Autowired
	ImGroupMessageService groupMessageService;
	
	@Autowired
	Publisher publisher;

	@Autowired
	StorePublisher storePublisher;
	
    /**
     * 建群操作 
     * 1. 插入数据库 group表，
     * 2. 插入数据库 group_user表
     * 3. 插入im_prichat_message 表 （邀请信息）
     * 3. 发送针对该群各用户的邀请通知
     * 
     * 处理消息
     * 
     * message:{ 
     *  action:'channelGroupCreate',
     *  msgType:'group',
     *  branchId:'归属机构号',
     *  categoryId:'归属分类编号', 
     *  cuserid:'群主编号',
     *  cusername:'群主姓名',
     *  cheadimgurl:'群主头像',
     * 	groupId:'群组编号为空则后台自动生成',
     *  groupName:'群组姓名为空则后台自动生成',
     *  bizId:'关联的业务主键比如项目测试小组编号',
     *  bizPid:'关联业务的父级主键比如项目编号',
     *  users:{
     *  	userid:'成员编号',
     *      username:'成员姓名',
     *      headimgurl:'成员头像'
     *  }
     * }
     */
    @Override
    public void doAction(JSONObject message) {
        JSONObject json = message;
        if (!json.containsKey("users")) {
            return;
        } 
        String groupId=json.getString("groupId");
        if(StringUtils.isEmpty(groupId)) {
        	groupId=seqService.getTablePK("group", "id");
        }else {
        	ImGroup groupDb=groupService.getImGroupByGroupId(groupId);
        	if(groupDb!=null && !StringUtils.isEmpty(groupDb.getId())) {
        		throw new BizException("已存在的群聊，不允许再创建");
        	}
        }
        String groupName=json.getString("groupName");
        String cusername=json.getString("cusername");
        String cuserid=json.getString("cuserid");
        String cheadimgurl=json.getString("cheadimgurl");
        if(StringUtils.isEmpty(cusername)) {
        	cusername=cuserid;
        }
        ImGroup group=new ImGroup();
        group.setId(groupId);
        group.setBranchId(json.getString("branchId"));
        group.setAllowJoin("1");
        group.setShopId(json.getString("shopId"));
        group.setCategoryId(json.getString("categoryId"));
        group.setCdate(new Date());
        group.setCuserid(cuserid);
        group.setCusername(cusername);
        group.setBizStatus("0");
        group.setGstatus("1");
        group.setIsPrichat("0");
        group.setLastUpdateTime(new Date());
        group.setBizId(json.getString("bizId"));
        group.setBizPid(json.getString("bizPid"));
        List<String> userids=new ArrayList<>();
        JSONArray jsonUsers=json.getJSONArray("users");
        List<ImGroupUser> groupUsers=new ArrayList<>();
        boolean haveCuserid=false;
        Map<String,Integer> useridOnlineStatus=new HashMap<>();
        for (Object user : jsonUsers) {
        	JSONObject jsonUser=(JSONObject)user;
        	String userid=jsonUser.getString("userid");
        	String username=jsonUser.getString("username");
        	String headimgurl=jsonUser.getString("headimgurl");
        	String status=jsonUser.getString("status");
        	ImGroupUser groupUser=new ImGroupUser();
        	if(cuserid.equals(userid)) {
        		groupUser.setJoinTime(new Date());
        		groupUser.setStatus("1");
        		haveCuserid=true;
        	}else {
        		if(StringUtils.isEmpty(status)) {
        			groupUser.setStatus("1");
        		}else {
        			groupUser.setStatus(status);
        		}
        		
        	}
        	groupUser.setUserid(userid);
        	groupUser.setUsername(username);
        	groupUser.setGroupId(groupId);
        	groupUser.setHeadimgurl(headimgurl);
        	groupUser.setStatus("1");
        	groupUser.setInviteTime(new Date());
        	groupUser.setId(groupUserService.createKey("id")); 
        	groupUsers.add(groupUser);
        	userids.add(userid); 
        }
        if(haveCuserid==false) {
        	ImGroupUser groupUser=new ImGroupUser();
        	groupUser.setJoinTime(new Date());
        	groupUser.setStatus("1");
        	groupUser.setUserid(cuserid);
        	groupUser.setStatus("1");
        	groupUser.setUsername(cusername);
        	groupUser.setGroupId(groupId);
        	groupUser.setHeadimgurl(cheadimgurl); 
        	groupUser.setInviteTime(new Date());
        	groupUser.setId(groupUserService.createKey("id")); 
        	groupUsers.add(groupUser);
        	userids.add(cuserid); 
        }
        if(StringUtils.isEmpty(groupName)) {
        	if(groupUsers.size()>2) {
        		groupName=groupUsers.get(0).getUsername()+","+groupUsers.get(1).getUsername()+"等参与的群聊";
        	}else if(groupUsers.size()==2){
        		groupName=groupUsers.get(0).getUsername()+","+groupUsers.get(1).getUsername()+"参与的聊天";
        	}else if(groupUsers.size()==1){
        		groupName=groupUsers.get(0).getUsername()+"建立的聊天";
        	}else {
        		groupName=cusername+"建立的聊天";
        	}
        	
        }  
        
        group.setGroupName(groupName); 
        json.put("groupName", groupName);
        json.put("groupId", groupId);
        json.put("isPrichat", "0");
        json.put("allowJoin", "1"); 
        json.put("gstatus", "1");  

        //如果是客户咨询问题 即 categoryId='css',自动分配在线的客服人员入群，自动剔除原来的客服人员
        if("css".equals(group.getCategoryId())) {
        	boolean needFenPeiCsworder=true;
        	//查询已分配的客服是否在线
        	for (ImGroupUser imGroupUser : groupUsers) {
				if(!cuserid.equals(imGroupUser.getUserid())) {
					if(useridOnlineStatus.get(imGroupUser.getUserid())==1) {
						needFenPeiCsworder=false;
						break;
					}
				}
			}
        	//如果已分配的客服人员不在线，需要重新分配客服人员
        	if(needFenPeiCsworder) {
        		//查询所有在线的并且正在接待的客户人数最少的客服专员，分配给该客户
        		List<Map<String,Object>> csworkers=groupUserService.selectOnlineAndMinCustCssWorkers(group.getBranchId(),cuserid,groupId,"css");
        		String workerId="";
        		String workerName="";
        		String workGroupId="";
        		boolean hasOnline=false;
        		for (Map<String, Object> worker : csworkers) {
        			workerId=(String) worker.get("userid");
        			workerName=(String) worker.get("username");
        			workGroupId=(String) worker.get("groupId");
					//检查是否在线
					hasOnline=ImLoginUtils.isOnline(workerId);
        	        if(hasOnline==true) {
        	        	break;
        	        }
				}
        		if(hasOnline==true) {
        			ImGroupUser groupUser=new ImGroupUser();
        			groupUser.setGroupId(groupId);
        			groupUser.setUserid(workerId);
        			groupUser.setUsername(workerName);
        			groupUser.setId(seqService.getTablePK("groupUser", "id"));
        			groupUser.setStatus("1");
        			groupUser.setInviteTime(new Date());
        			groupUser.setJoinTime(new Date());
        			groupUser.setLvl("0");
        			groupUsers.add( groupUser);
        		}else {
        			//如果没有在线的，从csworker列表中取第一个作为客服专员
        			if(csworkers!=null && csworkers.size()>0) {
        				Map<String,Object> worker=csworkers.get(0);
            			workerId=(String) worker.get("userid");
            			workerName=(String) worker.get("username");
            			workGroupId=(String) worker.get("groupId");
        				ImGroupUser groupUser=new ImGroupUser();
            			groupUser.setGroupId(groupId);
            			groupUser.setUserid(workerId);
            			groupUser.setUsername(workerName);
            			groupUser.setId(seqService.getTablePK("groupUser", "id"));
            			groupUser.setStatus("1");
            			groupUser.setInviteTime(new Date());
            			groupUser.setJoinTime(new Date());
            			groupUser.setLvl("0");
            			groupUsers.add( groupUser);
        			} 
        			
        		}
        		JSONObject workerfenpeiMessage=new JSONObject();
        		workerfenpeiMessage.put("msgId", seqService.getTablePK("messages", "msgId"));
        		workerfenpeiMessage.put("action", Action.NEW_MESSAGE);
        		workerfenpeiMessage.put("groupId", workGroupId);
        		workerfenpeiMessage.put("categoryId", "csw");
        		workerfenpeiMessage.put("channelId", "");
        		workerfenpeiMessage.put("sendUserid", workerId);
        		workerfenpeiMessage.put("sendUsername", workerName);
        		workerfenpeiMessage.put("groupId", workGroupId);
        		workerfenpeiMessage.put("store", "1");
        		workerfenpeiMessage.put("msgType", "group");
        		workerfenpeiMessage.put("sendContent", "分配客服人员【"+workerName+"】进行响应【"+cusername+"】的咨询");
        		workerfenpeiMessage.put("sendTime", new Date().getTime());
        		String workmsg=workerfenpeiMessage.toJSONString();
        		publisher.publishGroupMessage(workGroupId, workmsg);
				storePublisher.publishGroupMessageToDbQueue(workmsg);
        		
        		String messageStr=json.toJSONString();
        		publisher.publishGroupMessage(groupId, messageStr);
				storePublisher.publishGroupMessageToDbQueue(messageStr);
        		
        		JSONObject workmsgObj=workerfenpeiMessage;
        		workmsgObj.put("msgId", seqService.getTablePK("messages", "msgId")); 
        		workmsgObj.put("groupId", groupId); 
        		workmsgObj.put("categoryId", "css");
        		workmsgObj.put("sendContent", "客服人员【"+workerName+"】加入");
        		workmsgObj.put("sendTime", new Date().getTime());
        		workmsgObj.put("groupName", group.getGroupName()); 
        		workmsg=workmsgObj.toJSONString();
        		publisher.publishGroupMessage(groupId, workmsg);
				storePublisher.publishGroupMessageToDbQueue(workmsg);
				groupService.asyncCreateGroupAndBatchInsertUsers(group,groupUsers);
			}
        	
        }else {
        	if(super.execusePlugins(json)){
				String msg=json.toJSONString();
				publisher.publishGroupMessage(groupId, msg);
				storePublisher.publishGroupMessageToDbQueue(msg);

				groupService.asyncCreateGroupAndBatchInsertUsers(group,groupUsers);
			}
        }

        //super.handleMessageWithGroup(message,false,json.getString("groupId")); 
       
    }

}
